package crp.core.workflow.domain.services;

import com.qwlabs.cdi.Primary;
import com.qwlabs.jackson.Jackson;
import crp.core.workflow.domain.models.WorkflowInstanceEntity;
import crp.core.workflow.domain.repositories.WorkflowInstanceRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;

@ApplicationScoped
public class WorkflowInstanceSearcher {
    private final WorkflowInstanceRepository repository;
    private final WorkflowExternalInfoSearcher searcher;

    @Inject
    public WorkflowInstanceSearcher(WorkflowInstanceRepository repository,
                                    @Primary WorkflowExternalInfoSearcher searcher) {
        this.repository = repository;
        this.searcher = searcher;
    }

    public Stream<WorkflowInstanceEntity> byIds(Collection<String> ids) {
        return repository.findByIds(ids);
    }

    public Optional<WorkflowInstanceEntity> byId(String id) {
        return repository.findByIdOptional(id);
    }

    public String externalInfo(String externalId, String topic) {
        return Jackson.write(searcher.externalInfo(externalId, topic)).orElse("");
    }
}
